#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
PyQt6日志组件
提供统一的日志显示功能
"""

from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, 
                            QPushButton, QFileDialog, QGroupBox)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QTextCursor, QColor, QTextCharFormat, QFont
from datetime import datetime


class PyQt6LogComponent(QWidget):
    """PyQt6日志组件类"""
    
    def __init__(self, parent=None, title: str = "日志", height: int = 15):
        """
        初始化日志组件
        
        Args:
            parent: 父容器
            title: 日志框标题
            height: 日志框高度（行数）
        """
        super().__init__(parent)
        
        self.title = title
        self.height = height
        
        # 创建日志框架
        self.log_group = QGroupBox(title)
        layout = QVBoxLayout(self.log_group)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.setSpacing(5)
        
        # 创建日志文本框
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setFontFamily("Consolas")
        font = QFont()
        font.setPointSize(10)
        self.log_text.setFont(font)
        
        # 设置文本颜色格式
        self._setup_text_formats()
        
        layout.addWidget(self.log_text)
        
        # 创建控制按钮框架
        control_layout = QHBoxLayout()
        control_layout.setContentsMargins(0, 0, 0, 0)
        control_layout.setSpacing(5)
        
        # 清空日志按钮
        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.clicked.connect(self.clear_log)
        control_layout.addWidget(self.clear_btn)
        
        # 保存日志按钮
        self.save_btn = QPushButton("保存日志")
        self.save_btn.clicked.connect(self.save_log)
        control_layout.addWidget(self.save_btn)
        
        control_layout.addStretch()
        layout.addLayout(control_layout)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.addWidget(self.log_group)
    
    def _setup_text_formats(self):
        """设置文本格式"""
        self.formats = {
            "INFO": QTextCharFormat(),
            "WARNING": QTextCharFormat(),
            "ERROR": QTextCharFormat(),
            "DEBUG": QTextCharFormat(),
            "send": QTextCharFormat(),
            "receive": QTextCharFormat(),
            "normal": QTextCharFormat()
        }
        
        self.formats["INFO"].setForeground(QColor("black"))
        self.formats["WARNING"].setForeground(QColor("orange"))
        self.formats["ERROR"].setForeground(QColor("red"))
        self.formats["DEBUG"].setForeground(QColor("gray"))
        self.formats["send"].setForeground(QColor("blue"))
        self.formats["receive"].setForeground(QColor("green"))
        self.formats["normal"].setForeground(QColor("black"))
    
    def log_message(self, message: str, level: str = "INFO", msg_type: str = "normal"):
        """
        记录日志消息
        
        Args:
            message: 消息内容
            level: 日志级别 (INFO, WARNING, ERROR, DEBUG)
            msg_type: 消息类型 (normal, send, receive, error)
        """
        timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
        formatted_message = f"[{timestamp}] {message}\n"
        
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.MoveOperation.End)
        self.log_text.setTextCursor(cursor)
        
        # 根据消息类型选择格式
        if msg_type in self.formats:
            format_type = msg_type
        else:
            format_type = level
        
        cursor.setCharFormat(self.formats[format_type])
        cursor.insertText(formatted_message)
        self.log_text.ensureCursorVisible()
    
    def clear_log(self):
        """清空日志"""
        self.log_text.clear()
    
    def save_log(self):
        """保存日志到文件"""
        try:
            filename, _ = QFileDialog.getSaveFileName(
                self, 
                "保存日志",
                "",
                "文本文件 (*.txt);;所有文件 (*)"
            )
            
            if filename:
                content = self.log_text.toPlainText()
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(content)
                self.log_message(f"日志已保存到: {filename}")
        except Exception as e:
            self.log_message(f"保存日志失败: {e}", "ERROR")
    
    def get_content(self) -> str:
        """获取日志内容"""
        return self.log_text.toPlainText()